'use client'

import React, { createContext, useContext, useEffect, useState } from 'react'
import { ConfigProvider, theme } from 'antd'
import zhCN from 'antd/locale/zh_CN'

type Theme = 'light' | 'dark'

interface ThemeContextType {
    theme: Theme
    toggleTheme: () => void
    setTheme: (theme: Theme) => void
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined)

export const useTheme = () => {
    const context = useContext(ThemeContext)
    if (context === undefined) {
        throw new Error('useTheme must be used within a ThemeProvider')
    }
    return context
}

interface ThemeProviderProps {
    children: React.ReactNode
}

export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
    const [currentTheme, setCurrentTheme] = useState<Theme>('light')

    useEffect(() => {
        // 从localStorage读取主题设置
        const savedTheme = localStorage.getItem('medical-imaging-theme') as Theme
        if (savedTheme && (savedTheme === 'light' || savedTheme === 'dark')) {
            setCurrentTheme(savedTheme)
        } else {
            // 检测系统主题偏好
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
            setCurrentTheme(prefersDark ? 'dark' : 'light')
        }
    }, [])

    useEffect(() => {
        // 更新HTML data-theme属性
        document.documentElement.setAttribute('data-theme', currentTheme)
        // 保存到localStorage
        localStorage.setItem('medical-imaging-theme', currentTheme)
    }, [currentTheme])

    const toggleTheme = () => {
        setCurrentTheme(prev => prev === 'light' ? 'dark' : 'light')
    }

    const setTheme = (theme: Theme) => {
        setCurrentTheme(theme)
    }

    // Ant Design主题配置
    const antdTheme = {
        algorithm: currentTheme === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm,
        token: {
            colorPrimary: '#1890ff',
            colorSuccess: '#52c41a',
            colorWarning: '#faad14',
            colorError: '#ff4d4f',
            colorInfo: '#1890ff',
            borderRadius: 6,
            wireframe: false,
            // 自定义医学影像平台的设计令牌
            colorBgContainer: currentTheme === 'dark' ? '#1f1f1f' : '#ffffff',
            colorBgElevated: currentTheme === 'dark' ? '#262626' : '#fafafa',
            colorBorder: currentTheme === 'dark' ? '#434343' : '#d9d9d9',
            colorBorderSecondary: currentTheme === 'dark' ? '#303030' : '#f0f0f0',
        },
        components: {
            Card: {
                borderRadiusLG: 8,
                paddingLG: 16,
                boxShadowTertiary: currentTheme === 'dark'
                    ? '0 1px 2px 0 rgba(255, 255, 255, 0.03), 0 1px 6px -1px rgba(255, 255, 255, 0.02), 0 2px 4px 0 rgba(255, 255, 255, 0.02)'
                    : '0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02)',
            },
            Button: {
                borderRadius: 6,
                controlHeight: 32,
                paddingInline: 16,
            },
            Slider: {
                railBg: currentTheme === 'dark' ? '#434343' : '#f5f5f5',
                railHoverBg: currentTheme === 'dark' ? '#595959' : '#e1e1e1',
                trackBg: '#1890ff',
                trackHoverBg: '#40a9ff',
                handleColor: '#1890ff',
                handleActiveColor: '#096dd9',
            },
            Typography: {
                titleMarginTop: 0,
                titleMarginBottom: 8,
            },
            Layout: {
                bodyBg: currentTheme === 'dark' ? '#141414' : '#ffffff',
                headerBg: currentTheme === 'dark' ? '#1f1f1f' : '#ffffff',
                siderBg: currentTheme === 'dark' ? '#1f1f1f' : '#fafafa',
            },
        },
    }

    const contextValue: ThemeContextType = {
        theme: currentTheme,
        toggleTheme,
        setTheme,
    }

    return (
        <ThemeContext.Provider value={contextValue}>
            <ConfigProvider
                theme={antdTheme}
                locale={zhCN}
                componentSize="middle"
            >
                <div className={`theme-${currentTheme} fade-in`}>
                    {children}
                </div>
            </ConfigProvider>
        </ThemeContext.Provider>
    )
}

export default ThemeProvider